// ==UserScript==
// @name         IT之家夜间模式
// @namespace    http://tampermonkey.net/
// @version      1.0.4
// @updateURL    https://gist.githubusercontent.com/tomtiao/6bf711b7ee6c95b4cad5a28da13e3627/raw/main.js
// @description  根据设备状态自动切换夜间模式
// @author       tomtiao
// @include      /^https?:\/\/(?!dyn)[a-z0-9]+\.ithome\.com\/(?:(?:\d+\/\d+\/\d+\.htm)|(?:[0-9a-z]+\/))?$/
// @icon         https://www.ithome.com/favicon.ico
// @grant        none
// @run-at       document-body
// ==/UserScript==

(function() {
    'use strict';
    function buttonCache() {
        let btn = null;
        let div = null;
        return async function() {
            if (btn && div) return { switchBtnDiv: btn, innerDiv: div }
            return new Promise((resolve, reject) => {
                const f = () => {
                    const switchBtnDiv = document.querySelector('#dark-mode');
                    const innerDiv = switchBtnDiv.querySelector('div');
                    btn = switchBtnDiv;
                    div = innerDiv;
                    if (switchBtnDiv && innerDiv) {
                        resolve({ switchBtnDiv, innerDiv });
                    } else {
                        reject(new TypeError(`could not find switchBtnDiv or innerDiv`));
                    }
                };
                if (document.readyState === 'loading') {
                    window.addEventListener('DOMContentLoaded', f);
                } else {
                    f();
                }
            });
        }
    }
    const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    if (darkModeMediaQuery.media !== 'not all') {
        const getDarkModeBtnRefAsync = buttonCache();
        const actions = {
            turnOn: () => {
                document.body.classList.add('night');
                document.cookie = 'nightMode=1;path=/;domain=ithome.com;max-age=31536000';
                getDarkModeBtnRefAsync()
                .then(({ switchBtnDiv, innerDiv }) => {
                    switchBtnDiv.classList.add('night');
                    innerDiv.textContent = '夜间';
                })
                .catch(console.error);
            },
            turnOff: () => {
                document.body.classList.remove('night');
                document.cookie = 'nightMode=0;path=/;domain=ithome.com;max-age=31536000';
                getDarkModeBtnRefAsync()
                .then(({ switchBtnDiv, innerDiv }) => {
                    switchBtnDiv.classList.remove('night');
                    innerDiv.textContent = '白天';
                })
                .catch(console.error);
            }
        };
        const currentStatus = () => document.body.classList.contains('night');
        const f = (mediaQuery) => {
            if (mediaQuery.matches | currentStatus()) {
                mediaQuery.matches ? actions.turnOn() : actions.turnOff();
            }
        };
        f(darkModeMediaQuery);
        darkModeMediaQuery.addEventListener('change', f);
    }
})();